<!-- MessageSetting -->
<template>
  <div class="MessageSetting content_box">
    <div class="header_row flex align-center flex-wrap" v-if="hasBtn('messageSetting:query')">
      <div class="flex align-center m-r-2">
        <span>标题：</span>
        <el-input v-model="searchObj.Subject" clearable placeholder="搜索消息标题"></el-input>
      </div>

      <div class="flex align-center m-r-2">
        <span>时间：</span>
        <el-date-picker v-model="searchObj.timeValue" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" clearable>
        </el-date-picker>
      </div>

      <el-button type="primary" @click="(searchObj.currentPage = 1), getListFun()">查询</el-button>
    </div>

    <div class="m-b-1 neck_box flex align-center space-between">
      <div>
        <el-button type="success" @click="showDialog('add'),uploadLoading = false" v-if="hasBtn('messageSetting:add')">新增消息</el-button>
        <!-- <el-button type="danger">批量删除</el-button> -->
        <el-button type="warning" disabled v-if="hasBtn('messageSetting:export')">导出列表</el-button>
      </div>
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="searchObj.currentPage" :max-height="tableHeight" :page-size="searchObj.pageSize" :page-sizes="[10, 20, 50, 100, 200]" layout="total,sizes, prev, pager, next, jumper" :total="pageTotal">
      </el-pagination>
    </div>
    <el-table :data="tableData" border stripe style="width: 100%" @sort-change="sortChange" sortable="custom" v-loading="tableLoading" row-key="Id" @expand-change="expand">
      <el-table-column fixed prop="index" label="序号" width="80" align="center">
      </el-table-column>
      <el-table-column prop="Subject" label="标题" align="center" width="180" sortable>
      </el-table-column>

      <el-table-column prop="MessageType" label="消息类型" align="center" sortable>
        <template slot-scope="{ row }">
          <div>
            {{ findMessageType(row.MessageType) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="Content" label="内容" align="center" show-overflow-tooltip sortable>
        <template v-slot:default="slotProps">
          <div class="content" v-html="slotProps.row.Content"></div>
        </template>
      </el-table-column>
      <el-table-column prop="CreateBy" label="创建人员" align="center" sortable width="130">
      </el-table-column>
      <el-table-column prop="CreateDate" label="创建时间" align="center" width="180" sortable>
      </el-table-column>
      <el-table-column prop="UpdateBy" label="修改人员" align="center" sortable width="130">
      </el-table-column>
      <el-table-column prop="UpdateDate" label="修改时间" align="center" sortable width="180">
      </el-table-column>
      <el-table-column label="是否有效" align="center" sortable width="130">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.IsActive" :disabled="!hasBtn('messageSetting:active')" @change="switchChange(scope.row.Id, scope.row.IsActive)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="150" align="center" v-if="hasBtn('messageSetting:edit') || hasBtn('messageSetting:delete')">
        <template slot-scope="scope">
          <el-button type="primary" v-if="hasBtn('messageSetting:edit')" size="small" @click="handleEdit(scope.$index, scope.row),uploadLoading = false">编辑</el-button>
          <el-button @click="handleDelete(scope.$index, scope.row)" v-if="hasBtn('messageSetting:delete')" type="danger" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="dialogTitle" class="dialog" :visible.sync="dialogVisible" width="50%" destroy-on-close>
      <div v-loading="uploadLoading">
        <el-form ref="dataForm" :rules="rules" :model="addObj" label-position="right" label-width="140px">
          <el-form-item label="标题：" prop="Subject">
            <el-input class="flex-1" v-model="addObj.Subject"></el-input>
          </el-form-item>
          <el-form-item label="消息类型：" prop="MessageType">
            <el-select v-model="addObj.MessageType" placeholder="请选择">
              <el-option v-for="item in MessageTypeOption" :key="item.EnumName" :label="item.Desction" :value="item.EnumName">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="内容：" prop="text1area" v-if="addObj.MessageType == 'Notice'">
            <el-input type="textarea" class="flex-1" v-model="addObj.text1area" placeholder="请输入内容" maxlength="800" show-word-limit></el-input>
          </el-form-item>
        </el-form>
        <quill-editor v-if="addObj.MessageType != 'Notice'" v-model="addObj.Content" id="myQuillEditor" ref="myQuillEditor" :options="editorOption" />
      </div>
      <span slot="footer" class="dialog-footer">
        <span v-if="addObj.MessageType != 'Notice'" :class="length > 360000 ? 'color-red' : ''">内容总长度为: {{length}}/360000</span>
        <el-button @click="dialogVisible = false,uploadLoading = false">取 消</el-button>
        <el-button @click="saveData">保 存</el-button>
      </span>

    </el-dialog>

  </div>
</template>

<script>
  import { getList, save, deleteApi, valid, GetMessageType } from '@/api/message.js'
  import 'quill/dist/quill.snow.css'
  // import { quillEditor, Quill } from 'vue-quill-editor'
  import Quill from 'quill'
  import quillEditor from './components/editor.vue'

  import _ from 'lodash'
  const ICON_SVGS = {
    'table-insert-row': `<svg viewbox="0 0 18 18">
      <g class="ql-fill ql-stroke ql-thin ql-transparent">
        <rect height="3" rx="0.5" ry="0.5" width="7" x="4.5" y="2.5"></rect>
        <rect height="3" rx="0.5" ry="0.5" width="7" x="4.5" y="12.5"></rect>
      </g>
      <rect class="ql-fill ql-stroke ql-thin" height="3" rx="0.5" ry="0.5" width="7" x="8.5" y="7.5"></rect>
      <polygon class="ql-fill ql-stroke ql-thin" points="4.5 11 2.5 9 4.5 7 4.5 11"></polygon>
      <line class="ql-stroke" x1="6" x2="4" y1="9" y2="9"></line>
    </svg>`,
    'table-insert-column': `<svg viewbox="0 0 18 18">
      <g class="ql-fill ql-transparent">
        <rect height="10" rx="1" ry="1" width="4" x="12" y="2"></rect>
        <rect height="10" rx="1" ry="1" width="4" x="2" y="2"></rect>
      </g>
      <path class="ql-fill" d="M11.354,4.146l-2-2a0.5,0.5,0,0,0-.707,0l-2,2A0.5,0.5,0,0,0,7,5H8V6a1,1,0,0,0,2,0V5h1A0.5,0.5,0,0,0,11.354,4.146Z"></path>
      <rect class="ql-fill" height="8" rx="1" ry="1" width="4" x="7" y="8"></rect>
    </svg>`,
    'table-delete-row': `<svg viewbox="0 0 18 18">
      <g class="ql-fill ql-stroke ql-thin ql-transparent">
        <rect height="3" rx="0.5" ry="0.5" width="7" x="4.5" y="2.5"></rect>
        <rect height="3" rx="0.5" ry="0.5" width="7" x="4.5" y="12.5"></rect>
      </g>
      <rect class="ql-fill ql-stroke ql-thin" height="3" rx="0.5" ry="0.5" width="7" x="8.5" y="7.5"></rect>
      <line class="ql-stroke ql-thin" x1="6.5" x2="3.5" y1="7.5" y2="10.5"></line>
      <line class="ql-stroke ql-thin" x1="3.5" x2="6.5" y1="7.5" y2="10.5"></line>
    </svg>`,
    'table-delete-column': `<svg viewbox="0 0 18 18">
      <g class="ql-fill ql-transparent">
        <rect height="10" rx="1" ry="1" width="4" x="2" y="6"></rect>
        <rect height="10" rx="1" ry="1" width="4" x="12" y="6"></rect>
      </g>
      <rect class="ql-fill" height="8" rx="1" ry="1" width="4" x="7" y="2"></rect>
      <path class="ql-fill" d="M9.707,13l1.146-1.146a0.5,0.5,0,0,0-.707-0.707L9,12.293,7.854,11.146a0.5,0.5,0,0,0-.707.707L8.293,13,7.146,14.146a0.5,0.5,0,1,0,.707.707L9,13.707l1.146,1.146a0.5,0.5,0,0,0,.707-0.707Z"></path>
    </svg>`
  }
  const toolbarOptions = [
    ['bold', 'italic', 'underline', 'strike'], // toggled buttons
    ['blockquote', 'code-block'],

    [{ 'header': 1 }, { 'header': 2 }], // custom button values
    [{ 'list': 'ordered' }, { 'list': 'bullet' }],
    [{ 'script': 'sub' }, { 'script': 'super' }], // superscript/subscript
    [{ 'indent': '-1' }, { 'indent': '+1' }], // outdent/indent
    [{ 'direction': 'rtl' }], // text direction

    [{ 'size': ['small', false, 'large', 'huge'] }], // custom dropdown
    [{ 'header': [1, 2, 3, 4, 5, 6, false] }],

    [{ 'color': [] }, { 'background': [] }], // dropdown with defaults from theme
    [{ 'font': [] }],
    [{ 'align': [] }],
    //---开始
    [
      { 'table': 'TD' },
      { 'table-insert-row': 'TIR' },
      { 'table-insert-column': 'TIC' },
      { 'table-delete-row': 'TDR' },
      { 'table-delete-column': 'TDC' }
    ],
    //---结束
    ['image'],
    ['clean'] // remove formatting button
  ]

  export default {
    //import引入的组件需要注入到对象中才能使用
    name: 'MessageSetting',
    components: {},
    data() {
      //这里存放数据
      return {
        length: 0,
        uploadLoading: false,
        tableLoading: false,
        dialogVisible: false,
        dialogType: "add",
        searchObj: {
          Subject: "",
          timeValue: "",
          currentPage: 1,
          pageSize: 10,
        },
        tableHeight: 0,
        pageTotal: 0,
        tableData: [],
        rules: {
          Subject: [
            { required: true, message: '必填', trigger: 'blur' },
          ],
          MessageType: [{ required: true, message: '必填', trigger: 'blur' }]
        },
        addObj: {
          Content: ""
        },
        MessageTypeOption: [],
        editorOption: { // 富文本框参数设置
          placeholder: '',
          theme: 'snow', // or 'bubble'
          modules: {
            table: true, // 设为true
            toolbar: {
              container: toolbarOptions, // 工具栏
              handlers: {
                // 增加表格的5个触发方法
                'table': function (val) {
                  console.log('table====', this.quill.getModule('table'))
                  this.quill.getModule('table').insertTable(2, 3)
                },
                'table-insert-row': function () {
                  this.quill.getModule('table').insertRowBelow()
                },
                'table-insert-column': function () {
                  this.quill.getModule('table').insertColumnRight()
                },
                'table-delete-row': function () {
                  this.quill.getModule('table').deleteRow()
                },
                'table-delete-column': function () {
                  this.quill.getModule('table').deleteColumn()
                },

              }
            },
            // 下面是图片的扩展插件（图片支持调整大小）不需要可删掉
            // imageResize: {
            //   displayStyles: {
            //     backgroundColor: 'black',
            //     border: 'none',
            //     color: 'white',
            //   },
            //   modules: ['Resize', 'DisplaySize', 'Toolbar']
            // },
            // imageDrop: true
          }

        }
      };
    },
    components: { quillEditor },
    //监听属性 类似于data概念
    computed: {
      dialogTitle() {
        return this.dialogType == 'add' ? '新增方案' : '编辑方案'
      },
    },
    //监控data中的数据变化
    watch: {
      'addObj.Content': {
        handler(newVal) {
          console.log(newVal)
          if (newVal) {
            this.length = this.nameBytes(newVal)
          }
        },
        immediate: true
      },
      'addObj.text1area': {
        handler(newVal) {
          console.log(newVal)
          if (newVal) {
            this.length = this.nameBytes(newVal)
          }

        },
        immediate: true
      }
    },
    //方法集合
    methods: {
      findMessageType(e) {
        let obj = this.MessageTypeOption.find(_ => _.EnumName == e)
        if (obj) {
          return obj.Desction
        } else {
          return '空值'
        }
      },
      async GetMessageType() {
        let { Data } = await GetMessageType({})
        this.MessageTypeOption = Data
      },
      expand(row, expand) {
        console.log(row)
        if (!row.OpenExpand) {
          row.OpenExpand = true
          this.getDetail(row)
        }
      },
      async getDetail(row) {
        const { data } = await getExpandDetail({
          Id: row.Id
        })
        // row.Mains = data.Mains
        this.$set(row, 'Settings', data.Settings)
      },
      switchChange(id, IsActive) {
        valid({ Id: id }).then(_ => {
          this.$notify({
            title: '切换成功',
            message: 'success',
            type: 'success',
            duration: 2000
          })
          this.getListFun()
        })
      },
      showDialog(type) {
        if (type == 'add') {
          this.addObj = {
            "Id": "00000000-0000-0000-0000-000000000000",
            "Subject": "", //方案名称
            'Content': "",
            'MessageType': "",
          }
        }
        this.$nextTick(() => {
          setTimeout(() => {
            // let content = document.getElementById('myQuillEditor');
            this._initCustomToolbarIcon()
            // let dom = this.$refs.myQuillEditor.$el
            // this.quill = dom

          })
        })

        this.dialogType = type
        this.dialogVisible = true

      },

      nameBytes(str) {
        let personNameBytes = str.replace(/[^x00-xff]/g, '01').length
        return personNameBytes
      },


      saveData() {
        this.uploadLoading = true
        let addObj = this.$deepClone(this.addObj)
        if (addObj.MessageType == 'Notice') {
          addObj.Content = addObj.text1area
        }
        for (let item in addObj) {
          // if (['Remark'].includes(item)) continue
          if (!addObj[item] && addObj[item] !== 'Number') {
            this.$notify({
              title: '提示',
              message: '请填写完整信息',
              type: 'warning',
              duration: 2000
            })
            this.uploadLoading = false
            return
          }
        }
        console.log(addObj, this.nameBytes(addObj.Content))


        if (this.nameBytes(addObj.Content) > 360000) {
          this.$notify({
            title: '提示',
            message: '上传内容过大或致前端无法显示',
            type: 'warning',
            duration: 2000
          })
          this.uploadLoading = false
          return
        }

        save(addObj).then(res => {
          this.$notify({
            title: '保存成功',
            message: 'success',
            type: 'success',
            duration: 2000
          })
          this.dialogVisible = false
          this.getListFun()
        }).catch(err => {
          this.uploadLoading = false
        })

      },
      handleSizeChange(val) {
        this.searchObj.pageSize = val
        this.getListFun()
      },
      handleCurrentChange(val) {
        this.searchObj.currentPage = val
        this.getListFun()
      },

      handleEdit(index, row) {
        this.addObj = {
          "Id": row.Id,
          "Subject": row.Subject, //方案名称
          "Content": row.Content, //考核总交易量
          'MessageType': row.MessageType,
          'text1area': ""
        }
        if (row.MessageType == 'Notice') {
          this.addObj.text1area = row.Content
        } else {
          delete this.addObj.text1area
        }
        this.showDialog('edit')
      },
      handleDelete(index, row) {
        this.$confirm('确认删除此条数据吗？').then(_ => {
          let obj = {
            Id: row.Id
          }
          deleteApi(obj).then(res => {

            this.$notify({
              title: '删除成功',
              message: 'success',
              type: 'success',
              duration: 2000
            })
            this.tableData.splice(index, 1)
            this.pageTotal -= 1
          })
        })
        // this.getListFun()

      },
      sortChange(e) {
        let SortType = false
        if (e.order == "ascending") {
          SortType = true
        }
        this.getListFun(e.prop, SortType)
      },
      getListFun(SortName = 'CreateDate', SortType = true) {
        let currentPage = this.searchObj.currentPage
        this.tableLoading = true
        let searchObj = this.$deepClone(this.searchObj)
        let obj = {
          "Subject": searchObj.Subject, //	模块：指定整体管理模块设定
          "IsPaging": true, //是否分页
          "SortName": SortName, //排序栏位
          "SortType": SortType,//排序类型｛True：正序；Flase：反序｝
          'PageIndex': currentPage,
          "PageSize": searchObj.pageSize,
        }
        searchObj.timeValue && (obj['StartTime'] = searchObj.timeValue[0])//开始时间
        searchObj.timeValue && (obj['EndTime'] = searchObj.timeValue[1])//结束时间
        delete searchObj.timeValue
        getList(obj).then(res => {
          console.log(res)
          this.tableData = res.Data.map((item, index) => {
            for (let cell in item) {
              if (!item[cell] && this.$getType(item[cell]) !== 'Number') {
                item[cell] = '-'
              }
            }
            if (item.MessageType == 'Notice') {
              item.text1area = item.Content
            }
            return { ...item, index: (index + 1) + ((currentPage - 1) * 10) }
          })
          this.pageTotal = res.Total
          this.tableLoading = false
        }).catch(_ => {
          this.tableLoading = false
          this.tableData = []
          this.pageTotal = 0
        })
      },
      _initCustomToolbarIcon() {
        // 获取quill的原生图标库
        let icons = Quill.import('ui/icons')

        // 从自定义图标SVG列表中找到对应的图标填入到原生图标库中
        _.forEach(ICON_SVGS, (iconValue, iconName) => {
          icons[iconName] = iconValue
        })
      },
      onEditorChange(e) {
        console.log(e)
      },
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {
      this.GetMessageType()
      this.getListFun()
    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {

    },
    beforeCreate() { }, //生命周期 - 创建之前
    beforeMount() { }, //生命周期 - 挂载之前
    beforeUpdate() { }, //生命周期 - 更新之前
    updated() { }, //生命周期 - 更新之后
    beforeDestroy() { }, //生命周期 - 销毁之前
    destroyed() { }, //生命周期 - 销毁完成
    activated() { }, //如果页面有keep-alive缓存功能，这个函数会触发
  }
</script>
//@import url(); 引入公共css类
<style  scoped>
  .info_group {
    width: 65%;
  }
  /* .promoteB >>> .el-dialog {
      min-width: 560px;
    } */

  .ladder_item {
    width: 95%;
    border-bottom: 1px solid #cecece;
    padding: 5px 0;
  }
  .ladder_cell + .ladder_cell {
    border-top: 2px dashed #f6bcbc;
  }
  .ladder_cell {
    padding: 5px 0;
  }
  .ladder_name {
    /* width: 100px !important; */
    margin-right: 3%;
  }

  .el-icon-circle-close {
    font-size: 18px;
    transition: color 0.25s linear;
  }
  .el-icon-circle-close:hover {
    color: #cecece;
    cursor: pointer;
  }
  .table_ladname {
    width: 30%;
    font-size: 16px;
  }

  .MessageSetting >>> .editor {
    line-height: normal !important;
    height: 800px;
  }
  .MessageSetting >>> .ql-snow .ql-tooltip[data-mode='link']::before {
    content: '请输入链接地址:';
  }
  .MessageSetting >>> .ql-snow .ql-tooltip.ql-editing a.ql-action::after {
    border-right: 0px;
    content: '保存';
    padding-right: 0px;
  }

  .MessageSetting >>> .ql-snow .ql-tooltip[data-mode='video']::before {
    content: '请输入视频地址:';
  }

  .MessageSetting >>> .ql-snow .ql-picker.ql-size .ql-picker-label::before,
  .MessageSetting >>> .ql-snow .ql-picker.ql-size .ql-picker-item::before {
    content: '14px';
  }
  .MessageSetting
    >>> .ql-snow
    .ql-picker.ql-size
    .ql-picker-label[data-value='small']::before,
  .MessageSetting
    >>> .ql-snow
    .ql-picker.ql-size
    .ql-picker-item[data-value='small']::before {
    content: '10px';
  }
  .MessageSetting
    >>> .ql-snow
    .ql-picker.ql-size
    .ql-picker-label[data-value='large']::before,
  .MessageSetting
    >>> .ql-snow
    .ql-picker.ql-size
    .ql-picker-item[data-value='large']::before {
    content: '18px';
  }
  .MessageSetting
    >>> .ql-snow
    .ql-picker.ql-size
    .ql-picker-label[data-value='huge']::before,
  .MessageSetting
    >>> .ql-snow
    .ql-picker.ql-size
    .ql-picker-item[data-value='huge']::before {
    content: '32px';
  }

  .MessageSetting >>> .ql-snow .ql-picker.ql-header .ql-picker-label::before,
  .MessageSetting >>> .ql-snow .ql-picker.ql-header .ql-picker-item::before {
    content: '文本';
  }
  .MessageSetting
    >>> .ql-snow
    .ql-picker.ql-header
    .ql-picker-label[data-value='1']::before,
  .MessageSetting
    >>> .ql-snow
    .ql-picker.ql-header
    .ql-picker-item[data-value='1']::before {
    content: '标题1';
  }
  .MessageSetting
    >>> .ql-snow
    .ql-picker.ql-header
    .ql-picker-label[data-value='2']::before,
  .MessageSetting
    >>> .ql-snow
    .ql-picker.ql-header
    .ql-picker-item[data-value='2']::before {
    content: '标题2';
  }
  .MessageSetting
    >>> .ql-snow
    .ql-picker.ql-header
    .ql-picker-label[data-value='3']::before,
  .MessageSetting
    >>> .ql-snow
    .ql-picker.ql-header
    .ql-picker-item[data-value='3']::before {
    content: '标题3';
  }
  .MessageSetting
    >>> .ql-snow
    .ql-picker.ql-header
    .ql-picker-label[data-value='4']::before,
  .MessageSetting
    >>> .ql-snow
    .ql-picker.ql-header
    .ql-picker-item[data-value='4']::before {
    content: '标题4';
  }
  .MessageSetting
    >>> .ql-snow
    .ql-picker.ql-header
    .ql-picker-label[data-value='5']::before,
  .MessageSetting
    >>> .ql-snow
    .ql-picker.ql-header
    .ql-picker-item[data-value='5']::before {
    content: '标题5';
  }
  .MessageSetting
    >>> .ql-snow
    .ql-picker.ql-header
    .ql-picker-label[data-value='6']::before,
  .MessageSetting
    >>> .ql-snow
    .ql-picker.ql-header
    .ql-picker-item[data-value='6']::before {
    content: '标题6';
  }

  .ql-snow .ql-picker.ql-font .ql-picker-label::before,
  .ql-snow .ql-picker.ql-font .ql-picker-item::before {
    content: '标准字体';
  }
  .ql-snow .ql-picker.ql-font .ql-picker-label[data-value='serif']::before,
  .ql-snow .ql-picker.ql-font .ql-picker-item[data-value='serif']::before {
    content: '衬线字体';
  }
  .ql-snow .ql-picker.ql-font .ql-picker-label[data-value='monospace']::before,
  .ql-snow .ql-picker.ql-font .ql-picker-item[data-value='monospace']::before {
    content: '等宽字体';
  }
  .content {
    height: 40px;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
  .dialog-footer span {
    font-size: 16px;
    color: #8e8989;
    margin-right: 20px;
  }
  .color-red {
    color: #fe5656 !important;
  }
</style>
